
package com.probiz.estore.sales.model.action;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.common.model.cart.Shoppingcart;
import com.probiz.estore.common.model.cart.ShoppingcartItem;
import com.probiz.estore.common.model.product.ProductSku;

/**
 * CartFreeSkuDiscountAction get free XX(key=numItems) of sku YY(key=SKU)
 * 
 * @author ProBIZ
 * 
 */
public class CartGiftAction extends CartAbstractAction {
	private static final Log	logger				= LogFactory.getLog(CartGiftAction.class);
	public static final String	GIFT					= "GIFT";
	public static final String	DISCOUNT_QUANTITY	= "DISCOUNT_QUANTITY";
	public static final String	SEPARATOR_BEW_PARAM_AND_PARAM		= ",";
	public static final String	SEPARATOR_BEW_METHOD_AND_PERCENT	= "-";
	public static final String	FLAG_AFTER_AMOUNT					= "$";
	private String				paramSku;
	private int					paramDiscountQuantity;
	private Map<String, String>	params;

	public CartGiftAction(Map<String, String> _params) throws Exception {

		this.paramSku = _params.get(GIFT);
		this.paramDiscountQuantity = Integer.parseInt(_params
				.get(DISCOUNT_QUANTITY));

		this.params = _params;
	}

	public Map<String, String> getParams() {
		return params;
	}

	public Shoppingcart run(Shoppingcart _cart) {
		Shoppingcart cart = _cart;

		logger.debug(new StringBuffer().append("[DISCOUNT_QUANTITY|").append(
				paramDiscountQuantity).append("]").append("[GIFT|").append(
				paramSku).append("]").toString());
		for (ShoppingcartItem cartItem : cart.getShoppingCartItemsForPromoInCondition()) {
			if((cartItem.isCatalogConditionRunInAnyFlagRAM() && cartItem.isCatalogConditionGiftFlagRAM()) || !cartItem.isCatalogConditionGiftFlagRAM()){
				StringBuffer info = new StringBuffer();
				info.append(cart.getGainedGiftIds()).append(SEPARATOR_BEW_PARAM_AND_PARAM).append(paramSku).append(SEPARATOR_BEW_METHOD_AND_PERCENT).append(paramDiscountQuantity);
				cart.setGainedGiftIds(info.toString());
				if(!cartItem.isCatalogConditionGiftFlagRAM()){
					break;
				}
			}
		}
		return cart;
	}
	
	public ProductSku run(ProductSku _sku) {
		_sku.setCatalogConditionGiftRAM(true);
		StringBuffer info = new StringBuffer();
		info.append(_sku.getGiftValueIds()).append(SEPARATOR_BEW_PARAM_AND_PARAM).append(paramSku).append(SEPARATOR_BEW_METHOD_AND_PERCENT).append(paramDiscountQuantity);
		_sku.setGiftValueIds(info.toString());
		
		return _sku;
	}
}
